package com.xiaoq.shop.endpoint;

import com.alibaba.dubbo.config.annotation.Reference;
import com.xiaoq.apis.sites.ISitesApi;
import com.xiaoq.apis.sites.IZoneMasterApi;
import com.xiaoq.apis.sites.SitesInfo4SocialVo;
import com.xiaoq.coms.GenericDataResponse;
import com.xiaoq.coms.GenericListResponse;
import com.xiaoq.coms.GenericResponse;
import com.xiaoq.coms.util.ConstantUtil;
import com.xiaoq.shop.entity.SKUEntity;
import com.xiaoq.shop.entity.SPUCatalog;
import com.xiaoq.shop.service.ICatalogService;
import com.xiaoq.shop.service.ISKUService;
import com.xiaoq.shop.vo.SKUTicketDetailVo;
import com.xiaoq.shop.vo.SKUTicketVo;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by chenjh on 2017/11/3.
 */
@RestController
@RequestMapping(value = "/api/v1/shops")
public class TicketEndpoint2C {

    private static final Logger LOGGER = LoggerFactory.getLogger(TicketEndpoint2C.class);
    private static final class SKUTicketListResponse extends GenericListResponse<SKUTicketDetailVo> {};
    private static final class SKUTicketResponse extends GenericDataResponse<SKUTicketVo> {};
    private static final class SPUCatalogResponse extends GenericDataResponse<SPUCatalog> {};

    @Autowired
    private ISKUService skuService;

    @Autowired
    private ICatalogService catalogService;

    @Reference(interfaceClass=IZoneMasterApi.class, check=false, version="1.0.0")
    private IZoneMasterApi zoneMasterApi;

    @Reference(interfaceClass=ISitesApi.class, check=false, version="1.0.0")
    private ISitesApi sitesApi;

    @ApiOperation(value="购票的列表", notes="购票的列表")
    @ApiResponses({
            @ApiResponse(code = 200, response = SKUTicketDetailVo.class, message = "查询购票的列表")
    })
    @GetMapping(value="/{shopId}/tickets", produces={MediaType.APPLICATION_JSON_UTF8_VALUE})
    public ResponseEntity<?> ticketsList(@PathVariable("shopId") @ApiParam(value="店的ID", required=true) String shopId) {

        Map<String, List<SKUEntity>> specification2SKUMap = skuService.getTicketSkuMap(shopId, null, ConstantUtil.SALE_STATE_ON);
        List<SKUTicketDetailVo> skuTicketDetailVoList = new ArrayList<>();

        if(MapUtils.isEmpty(specification2SKUMap)){
            return SKUTicketListResponse.listNoCount(skuTicketDetailVoList);
        }

        Map<String, String> ticketCode2NameMap = catalogService.getTicketCode2TypeMap();

        String city = "";
        String sitesName = "";

        try {
            city = zoneMasterApi.getZoneNameBySitesId(shopId);
        } catch (Exception e) {
            LOGGER.error(e.getMessage() + " dubbo调用zoneMasterApi.getZoneNameBySitesId 失败", e);
        }

        try {
            SitesInfo4SocialVo siteInfo4Social = sitesApi.getSiteInfo4Social(shopId);
            if(siteInfo4Social != null){
                sitesName = siteInfo4Social.getName();
            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage() + " dubbo调用sitesApi.getSiteInfo4Social 失败", e);
        }

        for(Map.Entry<String, List<SKUEntity>> entry : specification2SKUMap.entrySet()){
            String specification = entry.getKey();
            List<SKUEntity> skuEntityList = entry.getValue();

            String ticketTypeName = ticketCode2NameMap.get(specification);
            SKUTicketDetailVo skuTicketDetailVo = new SKUTicketDetailVo();
            skuTicketDetailVo.setSpecification(specification);

            skuTicketDetailVo.setSpecificationName(ticketTypeName);
            skuTicketDetailVo.setCity(city);
            skuTicketDetailVo.setShopName(sitesName);

            List<SKUTicketVo> skuTicketVoList = new ArrayList<>();

            for(SKUEntity skuEntity : skuEntityList){
                SKUTicketVo skuTicketVo = transform2SKUTicketVo(skuEntity);
                skuTicketVo.setSpecificationsName(ticketTypeName);
                skuTicketVoList.add(skuTicketVo);
            }

            skuTicketDetailVo.setTicketList(skuTicketVoList);
            skuTicketDetailVoList.add(skuTicketDetailVo);
        }

        return SKUTicketListResponse.listNoCount(skuTicketDetailVoList);
    }


    @ApiOperation(value="通过skuId查询票信息", notes="通过skuId查询票信息")
    @ApiResponses({
            @ApiResponse(code = 200, response = SKUTicketResponse.class, message = "通过skuId查询票信息")
    })
    @GetMapping(value="/tickets/{skuId}", produces={MediaType.APPLICATION_JSON_UTF8_VALUE})
    public ResponseEntity<?> skuInfo(@PathVariable("skuId") @ApiParam(value="票的SKU_ID", required=true) String skuId) {

        SKUEntity skuEntity = skuService.getTicketSkuById(skuId);
        if(skuEntity == null || StringUtils.isBlank(skuEntity.getId())){
            return GenericResponse.ng("此票不存在");
        }

        if(skuEntity.getSaleState()==null || skuEntity.getSaleState().equals(ConstantUtil.SALE_STATE_OFF)){
            return GenericResponse.ng("此票已下线");
        }

        SKUTicketVo skuTicketVo = this.transform2SKUTicketVo(skuEntity);
        return SKUTicketResponse.okWithData(skuTicketVo);
    }

    private SKUTicketVo transform2SKUTicketVo(SKUEntity skuEntity){
        SKUTicketVo skuTicketVo = new SKUTicketVo();
        if(skuEntity != null){
            skuTicketVo.setBookNotices(skuEntity.getBookNotices());
            skuTicketVo.setShopId(skuEntity.getShopId());
            skuTicketVo.setDiscountPrice(skuEntity.getDiscountPrice()/100.0);
            skuTicketVo.setId(skuEntity.getId());
            skuTicketVo.setPrice(skuEntity.getPrice()/100.0);
            skuTicketVo.setMax2PermitPurchased(skuEntity.getMax2PermitPurchased());
            skuTicketVo.setSpecifications(skuEntity.getSpecifications());
            skuTicketVo.setSkuCode(skuEntity.getSkuCode());
            skuTicketVo.setSpuName(skuEntity.getSpuName());
            skuTicketVo.setTicketLabels(skuEntity.getTicketLabels());
            skuTicketVo.setSpuCode(skuEntity.getSpuCode());
            skuTicketVo.setPreSalePeriod(skuEntity.getPreSalePeriod());
            skuTicketVo.setSortIndex(skuEntity.getSortIndex());

            if(CollectionUtils.isNotEmpty(skuTicketVo.getTicketLabels())){
                skuTicketVo.getTicketLabels().forEach(ticketTag -> {
                    if(StringUtils.equals("1", ticketTag.getId())){
                        String title = ticketTag.getTitle();  //title 格式为 16:00
                        ticketTag.setTitle(title + "前可购当日门票");
                        String hourOfDayStr = "";
                        DateTime today = new DateTime();
                        if (StringUtils.isNotBlank(title) && title.contains(":") && StringUtils.isNumeric(hourOfDayStr = title.split(":")[0])) {
                            int hourOfDay = Integer.parseInt(hourOfDayStr);
                            DateTime today16EndTime = new DateTime(today.getYear(),
                                    today.getMonthOfYear(),
                                    today.getDayOfMonth(),
                                    hourOfDay,  //暂时为16点截止
                                    0);
                            if(today.getMillis() <= today16EndTime.getMillis()){
                                skuTicketVo.setCanOrderTodayTicket(1); // 可购买今日的门票
                            }else {
                                skuTicketVo.setCanOrderTodayTicket(0); // 不可购买今日的门票
                            }
                        }

                    }
                });
            }
        }
        return skuTicketVo;
    }



}